package T回溯;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author tmh
 * @date 2023/10/16 20:49
 * @description T_39组合总和
 */
public class T_39组合总和 {
    LinkedList<Integer> path = new LinkedList<>();
    List<List<Integer>> result = new LinkedList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backTracking(candidates, target,0);
        return result;
    }

    private void backTracking(int[] candidates, int target,int startIndex) {
        if (path.stream().mapToInt(i -> i).sum() > target) {
            return;
        }
        if (path.stream().mapToInt(i -> i).sum() == target) {
            result.add(new LinkedList<>(path));
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            path.add(candidates[i]);
            backTracking(candidates, target,i);
            path.removeLast();
        }
    }

    public static void main(String[] args) {
        T_39组合总和 t = new T_39组合总和();
        int[] array = {10,1,2,7,6,1,5};
        int target = 8;
        List<List<Integer>> list = t.combinationSum(array, target);
        System.out.println(list);
    }
}
